import { Controller } from 'egg';
import { saveImg } from '../utils/common/dealImg';
import { RESULT_CODE } from '../utils/constants/code';

export default class ExclusiveRestaurantController extends Controller {
  // 添加专属餐厅
  async addExclusiveRestaurant() {
    const { ctx } = this;

    const ret = await ctx.service.exclusiveRestaurantService.findExclusiveRestaurant();
    if(ret) {
      ctx.body = {
        code: RESULT_CODE.FAIL,
        message: '你已有专属餐厅或者正在审核',
      };
      return;
    }

    // 参数验证
    const rule = {
      name: { type: 'string', required: true, message: '餐厅名称不能为空' },
      description: { type: 'string', required: false },
    };

    ctx.validate(rule, ctx.request.body);

    try {
      const files = ctx.request.files;
      const data = Date.now(); // 毫秒数
      const ps:any = [];
      files && files.forEach((it:any, index:number) => {
        ps.push(saveImg({
          file: it,
          targetPath: this.config.uploadPathMap.exclusive_restaurants,
          ctx,
          fileName: data + index,
          isAutoClear: true,
        }));
      });
      const retPaths = await Promise.all(ps);
      const pictures = retPaths?.map(it => it).join(',');

      const result = await ctx.service.exclusiveRestaurantService.addExclusiveRestaurant({ ...ctx.request.body, pictures });
      
      ctx.body = {
        code: 200,
        message: '申请提交成功，等待审核',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  // 获取专属餐厅信息
  async getExclusiveRestaurantInfo() {
    const { ctx } = this;
    const { restaurant_id } = ctx.query as any;
    const ret = await ctx.service.exclusiveRestaurantService.findExclusiveRestaurant(restaurant_id);
    ctx.body = {
      code: 200,
      data: ret,
    };
  }

  // 更新专属餐厅信息
  async updateExclusiveRestaurant() {
    const { ctx } = this;

    const { name, description } = ctx.request.body;

    if (!name || !description) {
      ctx.throw(RESULT_CODE.FAIL, '参数不能为空');
    }

    try {
      const result = await ctx.service.exclusiveRestaurantService.updateExclusiveRestaurant({
        ...ctx.request.body,
      });

      ctx.body = {
        code: 200,
        message: '修改成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  async getExclusiveRestaurantApplyList() {
    const { ctx } = this;

    // 检查管理员权限
    if (!ctx.state.user.is_admin) {
      ctx.throw(403, '权限不足');
    }

    try {
      const result = await ctx.service.exclusiveRestaurantService.getApplicationList(ctx.query);
      
      ctx.body = {
        code: 200,
        message: '获取成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  // 审核
  async auditExclusiveRestaurant() {
    const { ctx } = this;

    // 检查管理员权限
    if (!ctx.state.user.is_admin) {
      ctx.throw(403, '权限不足');
    }

    // 参数验证
    const rule = {
      status: { type: 'enum', values: ['approved', 'rejected'], message: '状态值不正确' },
      remark: { type: 'string', required: false },
    };

    ctx.validate(rule);

    const { id, status, remark } = ctx.request.body;

    try {
      const result = await ctx.service.exclusiveRestaurantService.audit(parseInt(id), status, remark);
      
      ctx.body = {
        code: 200,
        message: result.message,
        data: null,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, error.message);
    }
  }

  // 添加分类
  async addCategory() {
    const { ctx } = this;

    const rule = {
      name: { type: 'string', required: true },
      icon: { type: 'string', required: false },
      sort_order: { type: 'int', required: false },
    };
    ctx.validate(rule, ctx.request.body);

    const { name, sort_order = 0, icon } = ctx.request.body;
    try {
      const ret = await ctx.service.exclusiveRestaurantService.addCategory(name, sort_order, icon);
      ctx.body = { code: 200, message: '添加成功', data: ret };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, (error as any).message);
    }
  }

  // 更新分类
  async updateCategory() {
    const { ctx } = this;
    const rule = {
      id: { type: 'int', required: true },
      name: { type: 'string', required: false },
      icon: { type: 'string', required: false },
      sort_order: { type: 'int', required: false },
    };
    ctx.validate(rule, ctx.request.body);
    const { id, name, sort_order, icon } = ctx.request.body;

    try {
      const ret = await ctx.service.exclusiveRestaurantService.updateCategory({ id: parseInt(id), name, sort_order, icon });
      ctx.body = { code: 200, message: '修改成功', data: ret };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, (error as any).message);
    }
  }

  // 删除分类
  async deleteCategory() {
    const { ctx } = this;
    const { id } = ctx.request.body;

    try {
      const ret = await ctx.service.exclusiveRestaurantService.deleteCategory(parseInt(id));
      ctx.body = { code: 200, message: ret.message, data: null };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, (error as any).message);
    }
  }

  // 添加菜品（支持多图 pictures）
  async addDish() {
    const { ctx } = this;

    const rule = {
      category_id: { type: 'int', required: true },
      name: { type: 'string', required: true },
      price: { type: 'number', required: false },
      description: { type: 'string', required: false },
      pictures: { type: 'string', required: false },
    };
    ctx.validate(rule, ctx.request.body);

    try {
      const result = await ctx.service.exclusiveRestaurantService.addDish({
        ...ctx.request.body,
      });

      ctx.body = {
        code: 200,
        message: '添加成功',
        data: result,
      };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, (error as any).message);
    }
  }

  // 删除菜品
  async deleteDish() {
    const { ctx } = this;
    const { id } = ctx.request.body;

    try {
      const ret = await ctx.service.exclusiveRestaurantService.deleteDish(parseInt(id));
      ctx.body = { code: 200, message: ret.message, data: null };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, (error as any).message);
    }
  }

  // 更新菜品（支持更新图片：pictures）
  async updateDish() {
    const { ctx } = this;
    const rule = {
      id: { type: 'int', required: true },
      name: { type: 'string', required: false },
      price: { type: 'number', required: false },
      is_hide: { type: 'number', required: false },
      description: { type: 'string', required: false },
      category_id: { type: 'int', required: false },
    };
    ctx.validate(rule, ctx.request.body);

    try {
      const payload = { ...ctx.request.body };
      const ret = await ctx.service.exclusiveRestaurantService.updateDish({
        id: parseInt(payload.id),
        is_hide: payload.is_hide,
        name: payload.name,
        price: payload.price ? Number(payload.price) : undefined,
        description: payload.description,
        pictures: payload.pictures,
        category_id: payload.category_id ? parseInt(payload.category_id) : undefined,
      });

      ctx.body = { code: 200, message: '修改成功', data: ret };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, (error as any).message);
    }
  }

  // 获取分类及分类下菜品列表
  async getCategoriesWithDishes() {
    const { ctx } = this;
    const { restaurant_id, filter_hide } = ctx.query as any;
    try {
      const data = await ctx.service.exclusiveRestaurantService.getCategoriesWithDishes({ restaurant_id, filter_hide });
      ctx.body = { code: 200, message: '获取成功', data };
    } catch (error) {
      ctx.throw(RESULT_CODE.FAIL, (error as any).message);
    }
  }
}